<template>
  <v-edit-title :element="element" :index="index" :total="total">
    <div ref="tableContainer" class="c-table-container">
      <div class="c-table-list">
        <div class="c-table-row__title"></div>
        <div
          v-for="(colItem, colIndex) in element.content.column"
          :key="colIndex"
          class="c-table-column__list"
        >
          <div class="c-table-column-header">
            <a-icon
              type="close"
              class="red editable-cell-icon"
              @click="removeColumn(colIndex)"
            />
            <v-edit-span v-model="colItem.header" />
            <a-icon
              type="edit"
              class="editable-cell-icon"
              @click="editColumn(colIndex)"
            />
          </div>
        </div>
      </div>
      <div
        v-for="(rowItem, rowIndex) in rowList"
        :key="rowIndex"
        class="c-table-list"
      >
        <div :ref="`row_${rowIndex}`" class="c-table-row__title">
          <!-- <editable-cell
            :text="rowItem"
            @change="onCellChange(rowIndex, $event)"
          /> -->
          {{ linkedTitle }}
        </div>
        <div
          v-for="(colItem, colIndex) in element.content.column"
          :key="colIndex"
          class="c-table-column__list"
        >
          <a-select
            :ref="`selectList_${rowIndex}_${colIndex}`"
            label-in-value
            :dropdown-match-select-width="false"
            @change="handleChange"
          >
            <a-select-option
              v-for="(item, index) in colItem.choices"
              :key="index"
              :value="`${rowIndex}_${colIndex}_${index}`"
            >
              {{ item.content }}
            </a-select-option>
          </a-select>
        </div>
      </div>
    </div>
    <div class="c-buttons">
      <a-select
        label-in-value
        :dropdown-match-select-width="false"
        class="link-button"
        :default-value="selectedValue"
        @change="linkQuestion"
      >
        <a-select-option
          v-for="item in targetLinkList"
          :key="item.id"
          :value="item.id"
        >
          {{ item.title }}
        </a-select-option>
      </a-select>
      <a-button @click="addColumn">添加一列</a-button>
    </div>
    <a-modal v-model="visible" title="编辑表格下拉框" @ok="handleOk">
      <p v-for="(item, index) in selectList" :key="index">
        <editable-cell
          :text="item.content"
          :if-can-edit="item.ifCanEdit"
          @change="onModalCellChange(index, $event)"
          @remove="onModalCellRemove(index)"
        />
      </p>
      <p><a-button @click="addModal">添加一行</a-button></p>
    </a-modal>
  </v-edit-title>
</template>
<script>
export default {
  props: {
    element: {
      type: Object,
      default() {
        return {
          title: '',
          content: [],
          id: -1,
        }
      },
    },
    index: Number,
    total: Number,
    source: {
      type: Array,
      default() {
        return []
      },
    },
    result: {
      type: Array,
    },
  },
  data() {
    return {
      activeEditColIndex: -1,
      visible: false,
      selectList: [],
      linkedTitle: '暂无关联题目',
      selectedValue: ''
    }
  },
  computed: {

    targetLinkList() {
      const list = []
      console.log('source', this.source)
      this.source.forEach((item, index) => {
        if (item.id === -1 || index === this.index - 1 || index === this.index) { return false }
        list.push(item)
      })
      const prevItem = this.source[this.index - 1]
      if (prevItem) {
        list.unshift(prevItem)
      }

      return list
    },
    options() {
      const list = []
      this.rowList.forEach((item, index) => {
        const obj = {
          row: item,
          column: [],
        }
        list[index] = obj
      })
      return list
    },
    rowList() {
      console.log('result', this.result)
      const list = this.element.content.row || []
      return list
      // const list = this.element.content.row
      // const outIdList = []
      // for (let i = 0; i < list.length; i++) {
      //   const item = list[i]
      //   if (typeof item.link) outIdList.push(item.link)
      // }

      // if (outIdList.length === 0) {
      //   return list
      // }
      // const tempList = []
      // for (let i = 0; i < this.result.length; i++) {
      //   const item = this.result[i]
      //   if (item && outIdList.includes(item.outId)) {
      //     const list = item.result.map((result) => {
      //       return result.content.replace(/(\w\.\s?)?/i, '')
      //     })
      //     tempList.push(list)
      //   }
      // }
      // const rowList = [].concat(...tempList)

      // return rowList
    },
  },
  created() {
    console.log('content', this.element.content)
    this.linkedTitle = this.getLinkTedTitle()
    this.selectedValue = this.getLinkedId()
    if (!this.element.content.row[0].shortNameList) { this.element.content.row[0].shortNameList = this.getShortNames() }
  },
  methods: {
    getShortNames() {
      const rowList = this.element.content.row || []
      const row = JSON.parse(JSON.stringify((rowList[0] || {})))
      delete row.link
      return Object.values(row)
    },
    getLinkTedTitle() {
      const list = this.element.content.row
      if (!list || list.length === 0) return '暂无关联题目'
      const linkId = list[0].link
      const target = this.source.find(item => (item.questionId === linkId) || (item.id === linkId))
      if (!target) return '暂无关联题目'
      return target.title.replace(/(\w\.\s?)?/i, '')
    },
    getLinkedId() {
      const list = this.element.content.row
      if (!list || list.length === 0) return '暂无关联题目'
      const linkId = list[0].link
      const target = this.source.find(item => (item.questionId === linkId) || (item.id === linkId))
      if (!target) return ''
      return target.id || target.questionId
    },
    onModalCellChange(index, value) {
      this.selectList[index].content = value
      console.log(this.selectList)
      this.element.content.column[this.activeEditColIndex].choices = JSON.parse(
        JSON.stringify(this.selectList)
      )
    },
    onModalCellRemove(index) {
      this.selectList.splice(index, 1)
      this.element.content.column[this.activeEditColIndex].choices = JSON.parse(
        JSON.stringify(this.selectList)
      )
    },
    addModal() {
      this.selectList.push({
        ifCanEdit: true,
        content: '',
        index: this.selectList.length + 1,
      })
    },
    handleOk() {
      this.visible = false
    },
    showModal() {
      this.visible = true
    },
    linkQuestion(e) {
      // this.element.content.row.push("行标题");
      console.log(e)
      this.linkedTitle = e.label
      const linkObj = this.element.content.row[0]
      linkObj.link = '' + e.key
      this.element.content.row.splice(0, 1, linkObj)
      console.log('content', JSON.stringify(this.element.content))
    },
    addColumn() {
      const id = this.element.content.column.length + 1
      this.element.content.column.push({
        header: '点击编辑列',
        columnId: id,
        choices: [],
      })
    },
    editColumn(colIndex) {
      const colItem = this.element.content.column[colIndex]
      this.selectList =
        colItem.choices.length > 0 ?
          colItem.choices :
          [
            {
              ifCanEdit: true,
              content: '',
              index: 1,
            },
          ]
      console.log('index', colIndex, colItem)
      this.activeEditColIndex = colIndex
      this.showModal()
    },
    removeColumn(colIndex) {
      this.element.content.column.splice(colIndex, 1)
      this.submit()
    },
    onCellChange(rowIndex, e) {
      console.log(rowIndex, e)
    },
    handleChange(item) {
      console.info('item:', item)
      const [rowIndex, colIndex, choiceIndex] = item.key.split('_')
      const columnList = this.element.content.column
      const column = columnList[colIndex]
      const choice = column.choices[choiceIndex]
      this.options[rowIndex].column[colIndex] = {
        title: column.header,
        choiceContent: choice.content,
      }
      this.submit()
    },
    submit() {
      this.$emit('complete', this.element.content)
    },
  },
}
</script>
<style scoped lang="less">
.c-buttons {
  width: 300px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.c-table-body {
  position: relative;
  .c-table-title-list {
    background: #fff;
    position: absolute;
    z-index: 1;
    left: 0;
    width: 80px;
    height: 100%;
    .c-table-row__title {
      height: 32px;
      line-height: 32px;
      margin-bottom: 20px;
      word-break: break-word;
      margin-right: 24px;
      text-align: right;
    }
  }
}
.link-button {
  width: 200px;
}
.c-table-container {
  overflow-x: scroll;
  font-size: 14px;
  color: #333;
}
.c-table-list {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
  margin-left: 120px;
  .c-table-column-header {
    word-break: break-word;
  }
  .c-table-column__list {
    width: 132px;
    display: flex;
    flex-direction: column;
    margin-right: 18px;
    & > div {
      width: 132px;
    }
  }
  .c-table-row__title {
    z-index: 1;
    word-break: break-word;
    position: absolute;
    left: -120px;
    width: 120px;
    margin-right: 24px;
    // text-align: right;
  }
}
.c-table-container::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 10px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 6px;
}

.c-table-container::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px;
  background: #999;
}

.c-table-container::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  background-color: #fff;
}
.red {
  color: red;
}
</style>
